<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use app\api\model\Account;
use app\api\model\LinUser;
use app\api\model\SdMaterial;
use app\api\model\SdModelEvent;
use app\api\model\SdScript;
use app\api\model\Upload;
use app\api\service\token\LoginToken;
use think\Db;
use think\Exception;
use think\Request;

require_once '../vendor/PHPExcel/Classes/PHPExcel/IOFactory.php';
require_once '../vendor/PHPExcel/Classes/PHPExcel/Reader/Excel5.php';
use PHPExcel;
use PHPExcel_IOFactory;

class Sd
{
    public function checkScript(Request $request) {
        $params = $request->post();
        $event = new SdScript();
        $count = $event->where("model", $params["model"])
            ->where("pid", $params["pid"])
            ->where("file_path", $params["file_path"])
            ->count();
        if ($count == 0) {
            return writeJson(200, false, '请求成功');
        } else {
            return writeJson(200, true, '请求成功');
        }
    }

    public function checkMaterial(Request $request) {
        $params = $request->post();
        $event = new SdMaterial();
        $query = $event->where("model", $params["model"])
            ->where("filename", $params["filename"]);
        if (isset($params["pid"])) {
            $query = $query->where("pid", $params["pid"]);
        }
        if (isset($params["pname"])) {
            $query = $query->where("pname", $params["pname"]);
        }
        $count = $query->findOrEmpty();

        if ($count->isEmpty()) {
            return writeJson(200, false, '请求成功');
        } else {
            return writeJson(200, $count["main_task_id"], '请求成功');
        }
    }

    public function addMaterial(Request $request) {
        $params = $request->post();
        $event = new SdMaterial();
        $res = $event->create($params);

        return writeJson(200, $res, '请求成功');
    }

    public  function addScript(Request $request)
    {
        $params = $request->post();
        $event = new SdScript();
        $params["pid"] = str_replace(" ", "", trim($params["pid"]));
        $params["pname"] = str_replace(" ", "", trim($params["pname"]));
        $event->create($params);

        return writeJson(200, '', '请求成功');
    }

    public function addEvent(Request $request) {
        $params = $request->post();
        $event = new SdModelEvent();
        $uid = LinUser::where("username", $params["model"])->findOrEmpty();
        if (!$uid->isEmpty()) {
            $params["uid"] = $uid["id"];
        }
        if (isset($params["script_id"])) {
            $script = SdScript::where("id", $params["script_id"])->findOrEmpty();
        } else {
            $script = SdScript::where("main_task_id", $params["main_task_id"])->findOrEmpty();
            $params["script_id"] = $script["id"];
        }
        if (!$script->isEmpty()) {
            $params["type"] = $script["type"];
            $event->create($params);
        }

        return writeJson(200, '', '请求成功');
    }

    public function getMaterial(Request $request)
    {
        $params = $request->post();
        $event = new SdMaterial();
        $list = $event->where("num", "<", 2)
            ->where("pid", $params["pid"])
            ->orderRand()->limit(3)
            ->select()->toArray();

        $savedata = [];
        if (!empty($list) && count($list) == 3) {
            foreach ($list as $li) {
                $old_num = $li["num"];
                $item = [];
                $item["id"] = $li["id"];
                $item["num"] = $old_num + 1;
                $savedata[] = $item;
            }
            $event->saveAll($savedata);
            return writeJson(200,$list,'成功！');
        } else {
            return writeJson(200,[],'成功！');
        }


    }

    public function backfillMaterial(Request $request)
    {
        $params = $request->post();
        $event = new SdMaterial();
        $list = $event->whereIn("id", $params["ids"])->select();
        $savedata = [];
        if (!empty($list)) {
            foreach ($list as $li) {
                $old_num = $li["num"];
                $item = [];
                $item["id"] = $li["id"];
                $item["num"] = $old_num - 1;
                $savedata[] = $item;
            }
            $event->saveAll($savedata);
        }
        return writeJson(200,true,'成功！');

    }

//    获取素材下单任务
    public function getOrderEvent()
    {
        $event = new SdModelEvent();
        $info = $event->where("status", 11)->where("is_top", 1)->lock(true)->findOrEmpty();
        if ($info->isEmpty()) {
            $info = $event->where("status", 11)->lock(true)->findOrEmpty();
        }
        if (!$info->isEmpty()) {
            $material = SdMaterial::field("main_task_id, num,url,is_kou")->where("main_task_id", $info["main_task_id"])->select()->toArray();
            $info["material"] = $material;

            if (!empty($info["script_id"])) {
                $script = SdScript::field("main_task_id, pimg, script")->where("id", $info["script_id"])->select()->toArray();
            } else {
                $script = SdScript::field("main_task_id, pimg, script")->where("main_task_id", $info["main_task_id"])->select()->toArray();
            }
            $info["product_script"] = $script;

            $info->status = 12;
            $info->save();
            return writeJson(200, $info, '请求成功');
        } else {
            return writeJson(200, [], '无');
        }
    }

    public function backfillEvent(Request $request)
    {
        $params = $request->post();
        $info = SdModelEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $info->save($params);
            return writeJson(200,$info,'成功！');
        } else {
            return writeJson(400,[],'找不到！');
        }
    }

    //    逛逛四版领取任务
    public function getVideoEvent(Request $request) {
        $event = new SdModelEvent();
        $info = $event->where("status", 1)
            ->where("is_top", 1)
//            ->where("id", 41660)
            ->where(function ($gather){
                $ten_min_ago = date("Y-m-d H:i:s", time() - 300);
                $gather->whereNull('get_time')->whereOr('get_time','<',$ten_min_ago);
            })
            ->findOrEmpty();
        if ($info->isEmpty()) {
            $info = $event->where("status", 1)
                ->where(function ($gather){
                    $ten_min_ago = date("Y-m-d H:i:s", time() - 300);
                    $gather->whereNull('get_time')->whereOr('get_time','<',$ten_min_ago);
                })
                ->findOrEmpty();
        }

        if (!$info->isEmpty()) {
//          检查口型配好没
            $upload = Upload::where("main_task_id", $info["main_task_id"])->whereNull("qiniu")->count();
            if ($upload == 0) {
//              配好了
                if (!empty($info["script_id"])) {
                    $jiaoben_info = SdScript::where("id", $info["script_id"])->findOrEmpty();
                } else {
                    $jiaoben_info = SdScript::where("main_task_id", $info["main_task_id"])->findOrEmpty();
                }
                $script = $jiaoben_info["script"];

                $upload_info = Upload::where("main_task_id", $info["main_task_id"])->select()->toArray();
                $material = SdMaterial::field("num,url")->where("main_task_id", $info["main_task_id"])->select()->toArray();

                $json_script = json_decode($script, true);
                foreach ($json_script as &$s) {
                    foreach ($upload_info as $u) {
                        if ($s["v"] == $u["number"] && $s["kou"] == '是') {
                            $s["path"] = $u["qiniu"];
                            $s["audio"] = $u["product_audio_url"];
                        }
                    }
                    foreach ($material as $m) {
                        if ($s["v"] == $m["num"] && $s["kou"] == '否') {
                            $s["path"] = $m["url"];
                        }
                    }
                }

                $info->status = 2;
                $info->get_time = date("Y-m-d H:i:s", time());
                $info->save();

                $info["jiaoben"] = $json_script;
                $info["title"] = $jiaoben_info["title"];
                $info["zimu_site"] = $jiaoben_info["zimu_site"];
                $info["zimu_size"] = $jiaoben_info["zimu_size"];
                $info["zimu_style"] = $jiaoben_info["zimu_style"];

                return writeJson(200, $info, '请求成功');

            } else {
                $info->get_time = date("Y-m-d H:i:s", time());
                $info->save();
                return writeJson(200, [], '无');
            }
        } else {
            return writeJson(200, [], '无');
        }
    }

    public function list(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $pageSize = $params['pageSize'] ?? 50;
        $event = new SdModelEvent();

        $query = $event->field("*");

        if ($uid != 1) {
            $query = $query->where("uid", $uid);
        }
        if (!empty($params["pid"])) {
            $query = $query->whereLike("pid", "%".$params["pid"]."%");
        }
        if (!empty($params["pname"])) {
            $query = $query->whereLike("pname", "%".$params["pname"]."%");
        }
        if (!empty($params["model"])) {
            $query = $query->whereLike("model", "%".$params["model"]."%");
        }
        if (!empty($params["type"])) {
            $query = $query->where("type", $params["type"]);
        }
        if (!empty($params["check"])) {
            $query = $query->where("check", $params["check"]);
        }
        if (!empty($params["status"])) {
            $query = $query->where("status", $params["status"]);
        }
        if (!empty($params["secondary"])) {
            $query = $query->where("category", $params["secondary"]);
        }
//        if (!empty($params["secondary"])) {
//            $query = $query->where("b.secondary", $params["secondary"]);
//        }
        if (!empty($params["start_time"])) {
            $query = $query->where("get_time", ">", $params["start_time"]);
        }
        if (!empty($params["end_time"])) {
            $query = $query->where("get_time", "<", $params["end_time"]);
        }
//        if (!empty($params["jd_export"])) {
//            if ($params["jd_export"] == 1) {
//                $query = $query->where("jd_export", $params["jd_export"]);
//            } else {
//                $query = $query->whereNull("jd_export");
//            }
//        }
        if (!empty($params["tb_export"])) {
            if ($params["tb_export"] == 1) {
                $query = $query->where("tb_export", $params["tb_export"]);
            } else {
                $query = $query->whereNull("tb_export");
            }
        }
        $list = $query->order("id desc")->paginate($pageSize);
        return writeJson(200,$list,'数据列表！');

    }

    public function resetEvent(Request $request)
    {
        $params = $request->get();
        $info = SdModelEvent::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            if ($info["status"] == 14) {
                $info->status = 11;
            }
            if ($info["status"] == 4) {
                $info->status = 1;
            }
            if ($info["status"] == 3) {
                Upload::where("main_task_id", $info["main_task_id"])->delete();
                $info->status = 11;
            }
            $info->save();
        }
        return writeJson(200, true, '请求成功');

    }

    // 后台提交脚本
    public function createScript(Request $request)
    {
        $params = $request->post();
        $data = json_decode($params["arr"], true);
        $uid = LoginToken::getInstance()->getCurrentUid();
        $res = 0;
        DB::startTrans();
        try {
            foreach ($data as $da) {
            $add = [];
            if ($da["zimuPoi"] == "上") {
                $add["zimu_site"] = 1;
            } elseif ($da["zimuPoi"] == "中") {
                $add["zimu_site"] = 2;
            } elseif ($da["zimuPoi"] == "下") {
                $add["zimu_site"] = 3;
            }

            $add["pid"] = $da["pid"];
            $add["pname"] = $da["pname"];
            $add["type"] = $da["type"];
            $add["model"] = $da["model"];
            $add["zimu_size"] = $da["zimuSize"];
            $add["zimu_style"] = $da["zimuStyle"];
            $add["title"] = $da["title"];
            $add["uid"] = $uid;
            $modifiedArray = array_map(function($item) {
                return [
                    "v" => str_replace("镜头", "", $item["len"]),
                    "t" => $item["text"],
                    "act" => $item["action"],
                    "yx" => $item["bgm"],
                    "tz" => $item["stickers"],
                    "kou" => $item["onCamera"]
                ];
            }, $da["lens"]);

            $add["script"] = json_encode($modifiedArray, 360);
            SdScript::create($add);
            $res += 1;
        }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,'失败！');
        }
        return writeJson(200, $res, '请求成功');

    }

    public function scriptList(Request $request)
    {
        $params = $request->post();
        $uid = LoginToken::getInstance()->getCurrentUid();

        $pageSize = $params['pageSize'] ?? 50;
        $event = new SdScript();


        if ($uid != 1) {
            $uname = LoginToken::getInstance()->getCurrentUserName();
            $query = $event->where("model", $uname);
        } else {
            $query = $event;
        }
        if (!empty($params["pid"])) {
            $query = $query->whereLike("pid", "%".$params["pid"]."%");
        }
        if (!empty($params["pname"])) {
            $query = $query->whereLike("pname", "%".$params["pname"]."%");
        }
        if (!empty($params["model"])) {
            $query = $query->whereLike("model", "%".$params["model"]."%");
        }
        if (!empty($params["type"])) {
            $query = $query->where("type", $params["type"]);
        }
        if (!empty($params["category"])) {
            $query = $query->where("category", $params["category"]);
        }
        if (!empty($params["start_time"])) {
            $query = $query->where("create_time", ">=", $params["start_time"]);
        }
        if (!empty($params["end_time"])) {
            $query = $query->where("create_time", "<", $params["end_time"]);
        }

        $list = $query->order("id desc")->paginate($pageSize);
        return writeJson(200,$list,'数据列表！');

    }

    public function getScriptById(Request $request)
    {
        $params = $request->get();
        $info = SdScript::where("id", $params["id"])->findOrEmpty();
        if ($info->isEmpty()) {
            return writeJson(200,[],'脚本不存在！');
        } else {
            return writeJson(200,$info,'数据列表！');
        }
    }

    public function modifyScript(Request $request)
    {
        $params = $request->post();
        $info = SdScript::where("id", $params["id"])->findOrEmpty();
        if (!$info->isEmpty()) {
            $res = SdScript::where("id", $info["id"])->update($params);

//            改变脚本类型
            if (isset($params["type"]) && $info["type"] != $params["type"]) {
                $sd_event = new SdModelEvent();
                $upload = new Upload();
                $event = $sd_event->where("script_id", $info["id"])->select()->toArray();
                if (!empty($event)) {
                    foreach ($event as $e) {
                        $sd_event->where("id", $e["id"])->update(["type"=>$params["type"]]);
                        $upload_info = $upload->where("main_task_id", $e["main_task_id"])->findOrEmpty();
                        if (!$upload_info->isEmpty()) {
                            $upload->where("main_task_id", $e["main_task_id"])->update(["type"=>$params["type"]]);
                        }
                    }
                }
            }
            return writeJson(200, $res, '请求成功');
        } else {
            return writeJson(200, "", '查询不到该脚本');
        }
    }

    // 小编导出用
    public function getListByIdForXB(Request $request)
    {
        $params = $request->get();
        $list = SdModelEvent::where("status", 3)->whereIn("id", $params["ids"])
            ->select()->toArray();

        return writeJson(200, $list, '请求成功');

    }

    // 八斗导出用
    public function getListById(Request $request)
    {
        $params = $request->get();
        $fifteenDaysAgo = strtotime('-15 days', time());

        DB::startTrans();
        try {
            $list = SdModelEvent::field("a.id,a.pid,a.model,a.pname,b.secondary,b.title as title_text, b.topic,url,cover,c.title,b.short_pname")
                ->alias('a')
                ->join("product_config b", "a.pid=b.pid")
                ->join("sd_script c", "a.script_id=c.id")
//                ->where("a.model", "林玺珍")
                ->where("a.status", 3)
                ->whereNull("tb_export")
                ->whereNull("a.category")
                ->where("a.get_time", ">=", date('Y-m-d H:i:s', strtotime('midnight', $fifteenDaysAgo)))
                ->whereIn("a.id", $params["ids"])->select()->toArray();

            if (!empty($list)) {
//                $account = Account::field("name,category,model_name")
//                    ->where("platform", "逛逛")->whereNotNull("model_name")->select()->toArray();
//                // 打乱数组顺序
//                shuffle($account);
                foreach ($list as $key=>$li) {
                    $list[$key]["account"] = "";
//                    foreach ($account as $ac) {
//                        $list[$key]["account"] = "";
//                        if ($ac["model_name"] == $li["model"] && strpos($ac["category"], $li["secondary"]) !== false) {
//                            $list[$key]["account"] = $ac["name"];
//                            break;
//                        }
//                    }
                }

//                foreach ($list as $li) {
//                    if (empty($li["account"])) {
//                        return writeJson(200, "", $li["model"]."-".$li["secondary"].'类别，没有可分配账号');
//                    }
//                    if (empty($li["topic"])) {
//                        return writeJson(200, "", $li["pname"].'topic为空');
//                    }
//                }
//                $res = SdModelEvent::whereIn("id", $ids)->update(["tb_export"=>1, "tb_backtime"=>date('Y-m-d H:i:s', time())]);

            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e, '请求失败');
        }

        return writeJson(200, $list, '请求成功');

    }

    public function importXHSExport(Request $request){
        $file = $request->file('file');
        $event = new SdModelEvent();

        $filename  = $file->getInfo()['tmp_name'];
        //设置excel格式
        $reader = PHPExcel_IOFactory::createReader('Excel2007');
        //载⼊excel⽂件
        $excel = $reader->load($filename);
        //读取第⼀张表
        $sheet = $excel->getSheet(0);
        //获取总⾏数
        $row_num = $sheet->getHighestRow();

        //获取总列数
        $col_num = 'C';
        $datas = []; //数组形式获取表格数据
        $head = [];
        $res = [];

        for($row=1;$row<=$row_num;$row++)
        {
            for($col='A';$col<=$col_num;$col++) {
                if ($row == 1) {
                    $head[] = $sheet->getCell($col."1")->getValue();
                } else {
                    $datas[$row-2][] = $sheet->getCell($col.$row)->getValue();
                }
            }
        }
//        $array2 = ["id","jd_export"];
//        if (array_diff_assoc($head, $array2) != NULL) {
//            return writeJson(200,false,'表结构不正确！');
//        }

        DB::startTrans();
        try {
            $save_data = [];

            for ($row = 0; $row < count($datas); $row++) {
                $add = [];
                $add["id"] = $datas[$row][0];
                $add["tb_export"] = $datas[$row][1];
//                $add["jd_url"] = $datas[$row][2];
                $add["tb_backtime"] = $datas[$row][2];
                $save_data[] = $add;
            }
            if (count($save_data) > 0) {
                $res = $event->saveAll($save_data);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,false,'导表失败！');
        }
        if (count($res) > 0) {
            return writeJson(200,count($res),'完成！');
        } else {
            return writeJson(200,0,'失败了！');

        }
    }

    // 八斗导出
    public function exportForBD(Request $request)
    {
        $params = $request->get();
        $fifteenDaysAgo = strtotime('-15 days', time());

        DB::startTrans();
        try {
            $query = SdModelEvent::field("a.id,a.pid,a.model,a.pname,b.secondary,b.title as title_text, b.topic,url,cover,c.title,b.short_pname")
                ->alias("a")
                ->join("product_config b", "a.pid=b.pid")
                ->join("sd_script c", "a.script_id=c.id")
                ->where("a.model", "林玺珍")
                ->where("a.status", 3)
//                ->where("check", 1)
                ->whereNull("tb_export")
                ->where("a.pid", "<>", "单品种草")
                ->where("a.pid", "<>", "好物分享")
                ->where("a.pid", "<>", "竞品对比")
                ->where("a.pid", "<>", "场景种草")
                ->where("a.create_time", ">=", date('Y-m-d H:i:s', strtotime('midnight', $fifteenDaysAgo)));

            if (isset($params["ids"]) && $params["ids"] != "") {
                $query = $query->whereIn("a.id", $params["ids"]);
            }
            if (isset($params["type"])) {
                $query = $query->where("a.type", $params["type"]);
                if ($params["type"] == 2) {
                    $query = $query->where("check", 1);
                }
            } else {
                return writeJson(20001, "", '请选择分类');
            }
            if (!empty($params["pname"])) {
                $query = $query->whereLike("pname", "%".$params["pname"]."%");
            }
            if (!empty($params["model"])) {
                $query = $query->whereLike("a.model", "%".$params["model"]."%");
            }
            if (!empty($params["start_time"]) && $params["start_time"] != "undefined") {
                $query = $query->where("create_time", ">", $params["start_time"]);
            }
            if (!empty($params["end_time"])  && $params["end_time"] != "undefined") {
                $query = $query->where("create_time", "<", $params["end_time"]);
            }
            $list = $query->select()->toArray();

            if (!empty($list)) {
                $data = [];
                $account = Account::field("name,category,model_name")
                    ->where("platform", "逛逛")->whereNotNull("model_name")->select()->toArray();

                foreach ($list as $li) {
                    $add = [];
                    foreach ($account as $ac) {
                        if ($ac["model_name"] == $li["model"] && $ac["category"] == $li["secondary"]) {
                            $add["account"] = $ac["name"];
                            break;
                        }
                    }
                    if (empty($li["title_text"])) {
                        return writeJson(200, "", $li["pname"].'title_text为空');
                    } else {
                        $title_parts = explode("=", $li["title_text"]);
                        $random_title = $title_parts[array_rand($title_parts)];
                    }

                    if (empty($li["topic"])) {
                        return writeJson(200, "", $li["pname"].'topic为空');
                    } else {
                        $topic_parts = explode("=", $li["topic"]);
                        $random_topic = $topic_parts[array_rand($topic_parts)];
                        $random_topic_parts = explode("-", $random_topic);
                    }

                    $add["id"] = $li["id"];
                    $add["secondary"] = $li["secondary"];
                    $add["title"] = $li["short_pname"]."，".$random_title;
                    $add["describe"] = $li["pname"]."，".$random_title;
                    $add["url"] = $li["url"];
                    $add["cover"] = $li["cover"];
                    $add["p_cover"] = "";
                    $add["link"] = "https://item.taobao.com/item.htm?id=".$li["pid"];
                    $add["topic_id"] = $random_topic_parts[0];
                    $add["topic"] = $random_topic_parts[1];
                    $data[] = $add;
                }

                $xlsName = date('YmdHis')."_八斗导出"; // 表名称
                $xlsCell = [
                    ['secondary', '自定义分类'],
                    ['account', '发布账号'],
                    ['title', '标题'],
                    ['describe', '描述'],
                    ['url', '视频路径'],
                    ['cover', '视频封面'],
                    ['p_cover', '封面图'],
                    ['link', '宝贝链接'],
                    ['topic_id', '逛逛话题编号'],
                    ['topic', '逛逛话题名称'],
                ];// 表头信息

//                dump($data);
                $this->downloadExcel($xlsName, $xlsCell, $data);// 传递参数
                $ids = [];
                foreach ($data as $da) {
                    $ids[] = $da["id"];
                }
                $res = SdModelEvent::whereIn("id", $ids)->update(["tb_export"=>1, "tb_backtime"=>date('Y-m-d H:i:s', time())]);

            } else {
                return writeJson(200, 0, '暂无数据');
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e, '请求失败');
        }
        return writeJson(200, $res, '请求成功');
    }

    public function exportForXHS(Request $request)
    {
        $params = $request->get();
        $fifteenDaysAgo = strtotime('-15 days', time());

        DB::startTrans();
        try {
            $query = SdModelEvent::field("id,pid,model,pname,url,cover")
                ->where("status", 3)
                ->where("check", 1)
                ->whereNull("xhs_export")
                ->where("create_time", ">=", date('Y-m-d H:i:s', strtotime('midnight', $fifteenDaysAgo)));;

            if (isset($params["ids"]) && $params["ids"] != "") {
                $query = $query->whereIn("id", $params["ids"]);
            }
            if (isset($params["type"])) {
                $query = $query->where("type", $params["type"]);
            }
            if (!empty($params["pname"])) {
                $query = $query->whereLike("pname", "%".$params["pname"]."%");
            }
            if (!empty($params["model"])) {
                $query = $query->whereLike("model", "%".$params["model"]."%");
            }
            if (!empty($params["start_time"]) && $params["start_time"] != "undefined") {
                $query = $query->where("create_time", ">", $params["start_time"]);
            }
            if (!empty($params["end_time"]) && $params["end_time"] != "undefined") {
                $query = $query->where("create_time", "<", $params["end_time"]);
            }
            $list = $query->select()->toArray();

            if (!empty($list)) {
                $data = [];

                foreach ($list as $li) {
                    $add = [];

                    $add["id"] = $li["id"];
                    $add["pid"] = $li["pid"];
                    $add["pname"] = $li["pname"];
                    $add["model"] = $li["model"];
                    $add["url"] = $li["url"];
                    $add["cover"] = $li["cover"];
                    $data[] = $add;
                }

                $xlsName = date('YmdHis')."_小红书导出"; // 表名称
                $xlsCell = [
                    ['id', 'id'],
                    ['pid', '产品id'],
                    ['pname', '产品名称'],
                    ['model', '模特'],
                    ['url', '视频路径'],
                    ['cover', '视频封面']
                ];// 表头信息

//                dump($data);
                $this->downloadExcel($xlsName, $xlsCell, $data);// 传递参数
                $ids = [];
                foreach ($data as $da) {
                    $ids[] = $da["id"];
                }
                $res = SdModelEvent::whereIn("id", $ids)->update(["xhs_export"=>1, "xhs_backtime"=>date('Y-m-d H:i:s', time())]);

            } else {
                return writeJson(200, 0, '暂无数据');
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(20001, $e, '请求失败');
        }
        return writeJson(200, $res, '请求成功');
    }

    public function downloadExcel($expTitle, $expCellName, $expTableData)
    {
        $xlsTitle    = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $cellNum     = count($expCellName);// 单元格长度
        $dataNum     = count($expTableData);
        $objPHPExcel = new \PHPExcel();// 引入库
        $cellName = [
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
        }

        // Miscellaneous glyphs, UTF-8  循环写入数据
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)
                    ->setCellValue($cellName[$j] . ($i + 2), (string)$expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//这一步非常关键，用来清除缓冲区防止导出的excel乱码
        $PHPWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");//创建生成的格式
        header('Content-Disposition: attachment;filename="'.$xlsTitle.'.xlsx"');//下载下来的表格名
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        return $PHPWriter->save('php://output');
    }

    public function batchCheck(Request $request){
        $params = $request->post();
        $ids = $params['ids'];

        $result = SdModelEvent::whereIn('id',$ids)->update([
            'check' => 1
        ]);
        return writeJson(200,$result,'批量检查！');
    }

    public function setTop(Request $request)
    {
        $params = $request->post();
        DB::startTrans();
        try {
            $info = SdModelEvent::where("id", $params["id"])->findOrEmpty();
            if (!$info->isEmpty()) {
                $flag = 1 - $info["is_top"];

                $info->is_top = $flag;
                $info->save();
                $upload = Upload::where("main_task_id", $info["main_task_id"])->update(["is_top"=>$flag]);

            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            return writeJson(200,0,'失败！');
        }
        return writeJson(200,$flag,'成功！');

    }

    public function copyScript(Request $request)
    {
        $params = $request->post();
        $event = new SdScript();
        $scripts = $event->whereIn("id", json_decode($params["ids"], true))->select()->toArray();
        $data = [];
        $num = 0;
        foreach ($scripts as $s) {
            $item = $s;
            $item["model"] = $params["model"];
            unset($item["id"]);
            unset($item["create_time"]);
            unset($item["update_time"]);
            $data[] = $item;
        }
        if (!empty($data)) {
            foreach ($data as $da) {
                $event->create($da);
                $num++;
            }
        }
        return writeJson(200,$num,'成功！');

    }

    //------------------------------------------逛逛五版-------------------------------------------------------------

    public function addEventByPname(Request $request) {
        $params = $request->post();
        $event = new SdModelEvent();
        $uid = LinUser::where("username", $params["model"])->findOrEmpty();
        if (!$uid->isEmpty()) {
            $params["uid"] = $uid["id"];
        }
        $params["type"] = 5; //逛逛5版
        $event->create($params);

        return writeJson(200, '', '请求成功');
    }

    public function getVideo()
    {
        $info = SdModelEvent::where("status", 1)
            ->where("is_top", 1)
            ->orderRand()->findOrEmpty();
        if ($info->isEmpty()) {
            $info = SdModelEvent::where("status", 1)
                ->orderRand()->findOrEmpty();
        }

        if (!$info->isEmpty()) {
            $randomItems = [];
            $randomids = [];

            if (empty($info["ids"])) {
                $list = SdMaterial::where("main_task_id", $info["main_task_id"])
                    ->where("num", 0)->select()->toArray();
                // 随机选取 8 个键名
                $randomKeys = array_rand($list, min(8, count($list)));
                // 提取随机元素
                foreach ((array)$randomKeys as $key) {
                    $randomids[] = $list[$key]["id"];
                    $randomItems[] = $list[$key]["url"];
                    SdMaterial::where("id", $list[$key]["id"])->update(["num"=>1]);
                }
                $info->ids = implode($randomids, ",");
            } else {
                $ids = explode(",", $info["ids"]);
                $list = SdMaterial::whereIn("id", $ids)->select()->toArray();
                foreach ($list as $li) {
                    $randomItems[] = $li["url"];
                }
            }

            $info->status = 2;
            $info->get_time = date("Y-m-d H:i:s", time());
            $info->save();

            $info["items"] = $randomItems;
            return writeJson(200, $info, '请求成功');
        } else {
            return writeJson(200, [], '无');
        }
    }
}